package com.fingard.dsp.bank.directbank.epay02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;

public class EPAY02Statement extends EPAY02Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        int totalNum = 0;
        int line = 0;
        String respCode = "";
        String respInfo = "";
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
            if (actItem != null) {
                FtpSet ftpSet = bankFront.getFtpSet("");

                WriteBankLogLn2("翼支付对账单SFTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
                String statementSendName = getBankConfig().getValueAsString("statementSendName");
                String statementRecName = getBankConfig().getValueAsString("statementRecName");

                if (StringHelper.isNullOrEmpty(statementSendName) && StringHelper.isNullOrEmpty(statementRecName)) {
                    retAts.writeRespCode("0");
                    retAts.writeRespInfo("请检查config中对账单的接收方'statementSendName'和发送方'statementRecName'配置!");
                    retAts.writeEnd();
                    return retAts;
                }
                //文件名命名规则：YYYYMMDD+推送对账文件方(TA)+_+接收对账文件方(TC).txt
                //文件名举例：20170915TA_TC.txt
                String downFileName = Format.Date8Format.format(p_reqQrySttm.getBusDate()) + statementSendName + "_" + statementRecName + ".txt";
                String localFilePath = createTempFileDirectory() + File.separator + downFileName;
                WriteBankLogLn2("翼支付对账单保存本地路径:" + localFilePath);

                SftpPortClient sftp = new SftpPortClient(ftpSet);
                String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
                WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                FtpReceiver ftpReceiver = sftp.downloadFile("", sftpFilePath, localFilePath);
                if (ftpReceiver.isCompleted) {
                    WriteBankLogLn2("翼支付对账单下载成功!");

                    String tmpStrRet = FileHelper.readFileText(localFilePath, getCharset());
                    WriteBankLogLn2("翼支付对账单响应数据:\r\n" + tmpStrRet);

                    /*
                     * 理赔流水号|保单号|订单号|出险日期|赔付方|支付流水号|赔付金额(分)
                     *    0        1      2      3      4       5         6
                     * 示例:
                     * LPZF2020061914462061399464|8G2029801202000000000168|212020060418421864297543654|2020-06-19|1|190723500011378849|73
                     * LPZF2020061914462125368357|8G2029801202000000000166|212020060416373248230039215|2020-06-19|1|190723500011378849|365
                     */

                    // 解析微保单笔实时收付对账单响应数据
                    if (StringHelper.hasAnyChar(tmpStrRet)) {
                        respCode = "0";
                        respInfo = "";
                        StringReader strReader = new StringReader(tmpStrRet);
                        BufferedReader tmpReader = new BufferedReader(strReader);
                        tmpReader.readLine();
                        while(true) {
                            String eachline = tmpReader.readLine();
                            if(eachline == null){
                                break;
                            }
                            String[] detailNodes = eachline.split("\\|");
                            if (detailNodes.length == 7) {
                                totalNum ++;
                                RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                if (StringHelper.hasAnyChar(detailNodes[0])) {
                                    tmpRetDetail.bkRefundSeq = detailNodes[0];
                                }
                                if (StringHelper.hasAnyChar(detailNodes[1])) {
                                    tmpRetDetail.srcNote = detailNodes[1];
                                }
                                if (StringHelper.hasAnyChar(detailNodes[3])) {
                                    tmpRetDetail.busTime = Format.DateTime14Format.format(Format.Date10Format.parse(detailNodes[3]));
                                }
                                if (StringHelper.hasAnyChar(detailNodes[0])) {
                                    tmpRetDetail.askNumber = detailNodes[0];
                                }
                                if (StringHelper.hasAnyChar(detailNodes[5])) {
                                    tmpRetDetail.transState = TransState.Success;
                                } else {
                                    tmpRetDetail.transState = TransState.Success;
                                }
                                if (StringHelper.hasAnyChar(detailNodes[6])) {
                                    tmpRetDetail.amount = StringHelper.amountDivide100(detailNodes[6]);
                                }
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        }
                    } else {
                        respCode = "-1";
                        respInfo = "翼支付对账单内容为空,请联系微保相关技术人员!";
                    }
                } else {
                    respCode = "-1";
                    respInfo = "翼支付对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
                }
            } else {
                respCode = "-1";
                respInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeTotalNum(String.valueOf(totalNum));
        retAts.writeRespCode(respCode);
        retAts.writeRespInfo(respInfo);
        retAts.writeEnd();
        return retAts;
    }
}
